package sago

import (
	"gopkg.in/gomail.v2"
	"strings"
	"sync"
)

//连接信息
const User = "chenweijie@mafengwo.com"
const Pass = "Chen7110363"
const Host = "smtp.exmail.qq.com"
const Port = 465

//邮件对象
type Mail struct {
	MailEngine *gomail.Dialer
}

var (
	mainOnce sync.Once
	MailEngine *gomail.Dialer
)

//初始化连接
func InitMailConnect() *gomail.Dialer {
	mainOnce.Do(func() {
		//获取邮件对象
		MailEngine = gomail.NewDialer(Host, Port, User, Pass)
	})
	return MailEngine
}

//发送邮件
func (mailInfo *Mail) SendEmail(mailToStr string, title string, body string) error {
	//转化成数组
	mailTo := strings.Split(mailToStr, ",")
	//消息队形
	messageInfo := gomail.NewMessage()
	//设置发送方
	messageInfo.SetHeader("From",  messageInfo.FormatAddress(User, "DPC")) //这种方式可以添加别名，即“XX官方”
	//设置接收方，可多个
	messageInfo.SetHeader("To", mailTo...)
	//设置主题
	messageInfo.SetHeader("Subject", title)
	//设置邮件正文
	messageInfo.SetBody("text/html", body)
	//发送
	err := mailInfo.MailEngine.DialAndSend(messageInfo)
	return err
}